package cn.b.sky.shop.activiti;

import cn.b.sky.common.constants.SystemConstant;
import cn.b.sky.common.exception.ImeException;
import cn.b.sky.user.dao.UserDao;
import cn.b.sky.user.service.model.Organization;
import cn.b.sky.user.service.model.Role;
import org.activiti.engine.identity.Group;
import org.activiti.engine.impl.persistence.entity.GroupEntity;
import org.activiti.engine.impl.persistence.entity.GroupEntityManager;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

public class CustomGroupEntityManager extends GroupEntityManager {
  private static final Logger LOGGER= LoggerFactory.getLogger(CustomGroupEntityManager.class);

  @Resource
  private UserDao userDao;

  @Override
  public List<Group> findGroupsByUser(String userId) {
    LOGGER.debug("findGroupsByUser : {}", userId);
    if (StringUtils.isBlank(userId)) {
      return null;
    }
    String[] user = userId.split(SystemConstant.USER_NAME_LINK);
    String userCode = user[0];
    String siteCode = user[1];
    if (user.length != 2) {
      throw ImeException.newException("groupManage_userId.M", new String[] { userId });
    }
    List<Group> groups = new ArrayList<Group>();
    //用户组织
    List<Organization> orgs = userDao.selectOrganizationByUser(siteCode, userCode);
    for (Organization org : orgs) {
      GroupEntity groupEntity = new GroupEntity(org.getOrganizationCode());
      groupEntity.setName(org.getOrganizationText());
      groupEntity.setType(SystemConstant.USER_ORG);
      groupEntity.setId(SystemConstant.USER_ORG + groupEntity.getId());
      groups.add(groupEntity);
    }

    List<Role> roles = userDao.selectRoleByUser(siteCode, userCode);
    for (Role role : roles) {
      GroupEntity groupEntity = new GroupEntity(role.getRoleCode());
      groupEntity.setName(role.getRoleText());
      groupEntity.setType(SystemConstant.USER_ROLE);
      groupEntity.setId(SystemConstant.USER_ROLE + groupEntity.getId());
      groups.add(groupEntity);
    }
    return groups;
  }

}